package com.example.first;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MapTask implements Runnable {
    private static final String TAG = "MapTask";
    Handler handler;
    HashMap<String, String> map;

    public void setHandler(Handler handler){
        this.handler = handler;
    }

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//
//    }

    public void run() {
        Log.i(TAG,"run:……");
        //耗时操作
        //获取网络数据
        List<HashMap<String,String>> ret = new ArrayList<HashMap<String,String>>();
        try{
            //使进度条的加载更明显
            Thread.sleep(3000);

            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
            //获取title
            Log.i(TAG,"title="+doc.title());
            Element title = doc.getElementsByTag("title").first();
            Elements trs = doc.getElementsByTag("tr");
            //提取网页中的所有汇率
            for(Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
                if(tds.size()>0){
                    String str = tds.get(0).text();
                    String val = tds.get(5).text();
                    HashMap map = new HashMap<String,String>();
                    Log .i(TAG,"run: td1 :"+ str+"的汇率为 "+val);
                    map.put("ItemTitle",str);
                    map.put("ItemDetail",val);
                    ret.add(map);
                }
            }
        }catch (IOException | InterruptedException e){
            e.printStackTrace();
        }

        //返回线程
        Message msg = handler.obtainMessage(9,ret);
        handler.sendMessage(msg);

    }

}